package com.zhaozhaonews.wemedia.interceptor;


import com.zhaozhaonews.model.wemedia.entity.WmUser;
import com.zhaozhaonews.util.thread.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * @author WanJl
 * @version 1.0
 * @title WmTokenInterceptor
 * @description
 * @create 2025/2/18
 */
@Slf4j
public class WmTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        Optional<String> optional = Optional.ofNullable(userId);
        if (optional.isPresent()) {
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.parseInt(userId));
            WmThreadLocalUtil.setUser(wmUser);
            log.info("WmTokenInterceptor....通过header请求头获取用户信息存入到ThreadLocal中");
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("清理本地线程..ThreadLocal....");
        WmThreadLocalUtil.clear();
    }
}
